home *** CD-ROM | disk | FTP | other *** search
- Path: anvil.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: REQUEST: Recursive functions
- Date: 1 Mar 1996 15:41:15 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4h81urINNuo@anvil.ugrad.cs.ubc.ca>
- References: <4h7lft$8ql@cis.clark.edu>
- NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
-
- In article <4h7lft$8ql@cis.clark.edu>,
- Michael Talmage <michaelt@clark.edu> wrote:
- >I need some help to write a recursive function that will move a mouse through
- >a maze to find some cheese at the end. My instructor did not really teach us
- >how to write recursive functions in class. Any help will be appreciated.
-
- Recursive functions are ones that call themselves. There can also be mutually
- recursive functions that call each other.
-
- They are good for representing a problem that can be given in terms of itself.
- For example, the fibonacci sequence can be defined recursively:
-
- fib(n) -- that is, the n-th fibonacci number starting from 0 -- is:
- 1 if n is 0;
- 1 if n is 1;
- or fib(n-1) + fib(n-2) otherwise.
-
- See, the computation of fib(x) requires fib(x-1) or fib(x-2). Recursion has to
- _terminate_ somewhere, hence we have conditions for just returning a value.
- Thus an explicit solution is given when the problem is recognized to be small
- enough.
-
- In the C language, a function do compute above might look like this:
-
- unsigned long fib(unsigned long n)
- {
- switch (n) {
- case 0:
- case 1:
- return 1;
- break;
- default:
- return fib(n-1) + fib(n-2);
- break;
- }
- /* notreached */
- }
-
- That is how you write a recursive function. In applying it to your problem, you
- have to come up with a recursive definition of the problem with the
- characteristic that the recursion stops when the solution is recognized (i.e.
- you enter the cell of the maze where the cheese is found).
-
- Assuming that the maze is based on a square grid, it is isomorphic to a
- tertiary tree (a tree with three possibly nil children at each node).
-
- room_1
- / | \
- left str right
- / \
- room_2 room_3
- / | \
- left str right
- \
- cheese_room
-
- The maze is really a tree, where you start at the root and make decisions about
- whether to go left, right or straight. Of course, this assumes that the maze
- does not contain loops.
-
- If the maze does not contain loops, traversing it is identical to a recursive
- traversal of the tree. By the way, the above tree might represent the maze:
-
- +-+-+
- |3 1|
- +-+ +
- |C 2|
- +-+-+ initial ``straight'' direction is <-
-
- There are other ways to define the problem, which change the representation and
- algorithm slightly.
- --
-
-